package org.qydjk.console.controller.product;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.product.*;
import org.qydjk.common.pojo.seller.Seller;
import org.qydjk.common.shiro.vo.ShiroUser;
import org.qydjk.common.util.ListUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.common.vo.ext.ProductLogEnum;
import org.qydjk.console.service.ICategoryService;
import org.qydjk.console.service.IProductService;
import org.qydjk.console.vo.ProductExtendsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 产品管理
 * Created by Edward_yang on 2017/12/20 0020.
 */
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController {
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IProductService productService;

    /***
     * 产品管理列表跳转
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/gotoProductInfo.do")
    public String gotoProductInfo() {
        return "product/productInfo";
    }

    /***
     * 产品数据列表加载
     * @author Edward_yang
     * @uptime 2017-12-201
     * @return
     */
    @RequestMapping("/productList.do")
    @ResponseBody
    public Object productList(Integer page, Integer rows, String sellerName, String productName, String verifyType, String status, String cityid, String classifyid, String labelid) {
        HibernatePage pager = new HibernatePage(page, rows);
        String sql = "SELECT  qp.id as id, qs.name as sellerName ,qp.name as productName, qp.img as productImg , qp.origin_price as originPrice ,qp.price as price, qp.repertory as repertory, qp.verify_type as verifyType, qp.status as status, qp.type as type ,qp.virtaul_comment_count  as virtaulCommentCount , qp.virtual_appointment_count as virtualAppointmentCount," +
                "  qp.virtual_collect_account as virtualCollectAccount, qp.virtual_sales_count as virtualSalesCount, qp.sales_count as salesCount, qp.comment_count as commentCount, qp.comment_score as commentScore,qp.appointment_count as appointmentCount, qp.collect_account as collectAccount, qp.create_time as createDate" +
                "  FROM  qy_seller qs ,qy_product qp " +
                " WHERE qs.id=qp.seller_id";
        String countSql = "SELECT count(qp.id) " +
                "  FROM  qy_seller qs ,qy_product qp " +
                " WHERE qs.id=qp.seller_id";
        if (!StringUtil.isEmptyOrNull(sellerName)) {
            sql += " and qs.name like'%" + sellerName + "%'";
            countSql += " and qs.name like'%" + sellerName + "%'";
        }
        if (!StringUtil.isEmptyOrNull(productName)) {
            sql += " and qp.name like'%" + productName + "%'";
            countSql += " and qp.name like'%" + productName + "%'";
        }
        if (!StringUtil.isEmptyOrNull(verifyType)) {
            if (!"-1".equals(verifyType)) {
                sql += " and qp.verify_type=" + verifyType;
                countSql += " and qp.verify_type=" + verifyType;
            }
        }
        if (!StringUtil.isEmptyOrNull(status)) {
            if (!"-1".equals(status)) {
                sql += " and qp.status=" + status;
                countSql += " and qp.status=" + status;
            }
        }
        //城市
        if (!StringUtil.isEmptyOrNull(cityid)) {
            if (!"-1".equals(cityid)) {
                String cityidSting=StringUtil.dotAddStartEnd(cityid);
                sql += " and qp.area_ids  like'%" + cityidSting + "%'";
                countSql += " and qp.area_ids  like'%" + cityidSting + "%'";
            }
        }
        //分类
        if (!StringUtil.isEmptyOrNull(classifyid)) {
            if (!"-1".equals(classifyid)) {
                String classifyidSting=StringUtil.dotAddStartEnd(classifyid);
                sql += " and qp.category_ids  like'%" + classifyidSting + "%'";
                countSql += " and qp.category_ids  like'%" + classifyidSting + "%'";
            }
        }
        //标签
        if (!StringUtil.isEmptyOrNull(labelid)) {
            if (!"-1".equals(labelid)) {
                String labelidSting=StringUtil.dotAddStartEnd(labelid);
                sql += " and qp.label_codes  like'%" + labelidSting + "%'";
                countSql += " and qp.label_codes  like'%" + labelidSting + "%'";
            }
        }
        sql += " ORDER BY  qp.create_time desc";
        try {
            List<Map<String, Object>> productList = baseService.findMapBySQL(sql, pager);
            int total = baseService.getRecordCountSQL(countSql);
            return new EasyUIResponse(total, productList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /***
     * 产品添加页面跳转
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/gotoAddProudct.do")
    public String gotoAddProudct() {
        return "product/product_add";
    }

    /***
     * 添加产品去查询商家
     * @author Edward_yang
     * @uptime 2017-12-24
     */
    @RequestMapping("/addProudctGuerySelllerList.do")
    @ResponseBody
    public Object addProudctGuerySelllerList(Integer page, Integer rows, String phone, String sellerName) {
        HibernatePage pager = new HibernatePage(page, rows);
        String sql = "SELECT qs.id as id ,qu.phone as userZH, qs.name as sellerName, qs.logo as sellerLogo ,qs.verify_type as verifyType ,qs.status as status,qs.tel as tel,qs.address as address ,qs.virtaul_comment_count as virtaulCommentCount ,qs.comment_count as commentCount, qs.comment_score as commentScore ,qs.virtual_appointment_count as virtualAppointmentCount , qs.create_time as createDate , " +
                "  qs.settlement_ratio as settlementRatio,qs.virtual_collect_account  as virtualCollectAccount ,qs.appointment_count  as appointmentCount,qs.collect_account  as collectAccount ,qs.ord as ord ,qs.area_ids as areaIds,qs.appointment_info as  appointmentInfo, qs.buy_info as buyInfo " +
                "  From qy_seller qs, qy_user qu " +
                "  where qs.user_id=qu.id";
        String sqlCount = "SELECT count(qs.id) " +
                "  From qy_seller qs, qy_user qu " +
                "  where qs.user_id=qu.id";
        if (!StringUtil.isEmptyOrNull(phone)) {
            sql += " and qu.phone=" + phone;
            sqlCount += " and qu.phone=" + phone;
        }
        if (!StringUtil.isEmptyOrNull(sellerName)) {
            sql += " and qs.name like'%" + sellerName + "%'";
            sqlCount += " and qs.name like'%" + sellerName + "%'";
        }
        sql += " ORDER BY  qs.create_time desc";
        try {
            List<Map<String, Object>> sellerList = baseService.findMapBySQL(sql, pager);
            int total = baseService.getRecordCountSQL(sqlCount);

            return new EasyUIResponse(total, sellerList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 添加产品
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object addProudct(ProductExtendsBean productExtendsBean) {
        ShiroUser shiroUser = getShiroUser();
        try {
            String[] categoryIdsArr = request.getParameterValues("categoryIds");
            String categoryIds = ListUtil.arrToString(categoryIdsArr);
            String catids = categoryService.findAllByLeafIds(categoryIds);
            productExtendsBean.setCategoryIds(catids);
            Boolean ss = productService.addProductALlInfo(productExtendsBean, shiroUser, request);
            if (ss) {
                return renderSuccess();
            } else {
                return renderError("添加数据存在问题");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 产品编辑页面跳转
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/gotoEditProudct.do")
    public String gotoEditProudct(Integer productId) {
        try {
            Product product = baseService.get(Product.class, productId);
            //逗号处理
            String leafCatIds = categoryService.findAllNoParentCatIds(StringUtil.dotWipeStartEnd(product.getCategoryIds()));
            product.setCategoryIds(leafCatIds);
            product.setAreaIds(StringUtil.dotWipeStartEnd(product.getAreaIds()));
            product.setCategoryIds(StringUtil.dotWipeStartEnd(product.getCategoryIds()));
            Seller seller = baseService.get(Seller.class, product.getSellerId());
            request.setAttribute("product", product);
            request.setAttribute("seller", seller);
            List<ProductImgs> productImgsList = baseService.findBeanBySQL(" select * from qy_product_imgs where product_id=" + product.getId(), ProductImgs.class);
            String imgsString = "";
            for (ProductImgs imgs : productImgsList) {
                imgsString += imgs.getImg() + ",";
            }
            request.setAttribute("imgsString", imgsString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "product/product_edit";
    }

    /***
     *编辑产品
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object editProudct(ProductExtendsBean productExtendsBean) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Boolean ss = productService.updateProductALlInfo(productExtendsBean, shiroUser, request);
            if (ss) {
                return renderSuccess();
            } else {
                return renderError("编辑数据存在问题");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 删除产品
     * @author Edward_yang
     * @uptime 2017-12-21
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteProudct(Integer productId) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Product product = baseService.get(Product.class, productId);
            baseService.delete(product);
            //日志
            ProductLog productLog = new ProductLog();
            productLog.setProductId(product.getId());
            productLog.setUserId(shiroUser.getId()); //管理员id
            productLog.setType(ProductLogEnum.DELETE.getType());
            productLog.setTypeName(ProductLogEnum.DELETE.getTypeName());
            productLog.setUsername(shiroUser.getName());//管理员名称
            productLog.setCreateTime(new Date());
            productLog.setUpdateTime(new Date());
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 跳转审核产品
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/gotoCheckProduct.do")
    public String gotoCheckProduct(Integer productId) {
        try {
            Product product = baseService.get(Product.class, productId);
            request.setAttribute("product", product);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "product/product_checkProduct";
    }

    /**
     * 审核产品
     *
     * @return
     * @author Edward_yang
     * @uptime 2017-12-20
     */
    @RequestMapping("/checkProduct.do")
    @ResponseBody
    public Object checkProduct(Integer productId, Integer productType) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Product product = baseService.get(Product.class, productId);
            Seller seller = baseService.get(Seller.class, product.getSellerId());
            if(product.getVerifyType()==productType){
                //相同不操作
            }else{
                //如果产品上架 商家产品数量+1
                if(productType==1){
                    seller.setProductCount(seller.getProductCount()+1);
                }else{
                    if(seller.getProductCount()>0){
                        seller.setProductCount(seller.getProductCount()-1);
                    }
                }
                product.setVerifyType(productType);
                product.setUpdateTime(new Date());
                baseService.saveOrUpdate(product);
            }
            String sql="SELECT MIN(price) as price FROM qy_product WHERE verify_type=1 and seller_id=" + product.getSellerId();
            List<Map<String,Object>> price=baseService.findMapBySQL(sql);
            //如果是空的默认为0
            if(price.get(0).get("price")==null){
                seller.setInitiatePric(new BigDecimal(0));
            }else{
                seller.setInitiatePric(new BigDecimal(price.get(0).get("price").toString()));
            }
            baseService.update(seller);
            //日志
            ProductLog productLog = new ProductLog();
            productLog.setProductId(product.getId());
            productLog.setUserId(shiroUser.getId()); //管理员id
            productLog.setUsername(shiroUser.getName());//管理员名称
            productLog.setType(ProductLogEnum.APPLY_PUTAWAY.getType());
            productLog.setTypeName(ProductLogEnum.APPLY_PUTAWAY.getTypeName());
            productLog.setCreateTime(new Date());
            productLog.setUpdateTime(new Date());
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }


    /****
     * 跳转商家启用和禁用
     * @author Edward_yang
     * @uptime 2017-12-21
     * @return
     */
    @RequestMapping("/gotoCheckStauteProduct.do")
    public String gotoCheckStauteProduct(Integer productId) {
        try {
            Product product = baseService.get(Product.class, productId);
            request.setAttribute("product", product);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "product/proudct_checkStauteProudct";
    }

    /***
     *  商家启用和禁用
     * @author Edward_yang
     * @uptime 2017-12-21
     * @return
     */
    @RequestMapping("/checkStauteProduct.do")
    @ResponseBody
    public Object checkStauteProduct(Integer productId, Integer status) {
        try {
            Product product = baseService.get(Product.class, productId);
            product.setStatus(status);
            product.setUpdateTime(new Date());
            baseService.saveOrUpdate(product);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 服务标签
     * @author Edward_yang
     * @uptime 2017-12-26
     * @param productId
     * @return
     */
    @RequestMapping("/gotoeditProductServeLabel.do")
    public String gotoeditProductServeLabel(Integer productId) {
        try {
            Product product = baseService.get(Product.class, productId);

            //获取全部标签  //获取商家选中的ID 做数据初始化
            List<Map<String, Object>> serveLabelList = baseService.findMapBySQL("SELECT qsl.ord as ord ,qsl.id as id ,qsl.class_property_text as name FROM  qy_serve_label qsl  WHERE  qsl.id  in (SELECT qssl.serve_label_id as  serveLabelId  FROM qy_seller_serve_label qssl WHERE qssl.seller_id=" + product.getSellerId() + ")");
            //获取产品选中的
            String sql = "SELECT concat(qpsl.serve_label_id,'_',qpsl.ord) AS X  FROM qy_product_serve_label qpsl WHERE qpsl.product_id=" + productId;
            List<Object> productserveLabelList = baseService.findSingleColumnListBySQL(sql);
            request.setAttribute("serveLabelList", serveLabelList);
            request.setAttribute("product", product);
            request.setAttribute("productserveLabelList", productserveLabelList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/product/product_editProductServeLabel";
    }


    /***
     * 保存商家服务标签
     * @author Edward_yang
     * @uptime 2017-12-26
     * @param productId
     * @param serveLabelList
     * @return
     */
    @RequestMapping("/editProductServeLabel.do")
    @ResponseBody
    public Object editProductServeLabel(String serveLabelList, Integer productId) {
        try {
            baseService.excuteSQL("DELETE FROM qy_product_serve_label WHERE product_id =" + productId);//产品服务标签
            String[] serveLabelLists = serveLabelList.split(",");
            for (int i = 0, len = serveLabelLists.length; i < len; i++) {
                String[] serveLabelListss = serveLabelLists[i].toString().split("_");
                System.out.println(serveLabelListss[0].toString());
                System.out.println(serveLabelListss[1].toString());
                ProductServeLabel productServeLabel = new ProductServeLabel();
                productServeLabel.setProductId(productId);
                productServeLabel.setCreateTime(new Date());
                productServeLabel.setUpdateTime(new Date());
                productServeLabel.setServeLabelId(Integer.valueOf(serveLabelListss[0].toString()));
                productServeLabel.setOrd(Integer.valueOf(serveLabelListss[1].toString()));
                baseService.save(productServeLabel);
            }
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 产品自动补全
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object autoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        try {
            String query = request.getParameter("query");
            query = StringUtil.iosToUTF8(query).trim();
            if("".equals(query)){return null;}
            System.out.println(query);
            if (StringUtil.isEmptyOrNull(query)) {
                return new AutoCompleteResponse(list);
            }
            String sql = "SELECT name as `value`,concat(id,'') AS `data` FROM qy_product WHERE status=1 and verify_type=1 and name LIKE '%"+ query +"%'";
            list = baseService.findBeanBySQL(sql,AutoCompleteBean.class,new HibernatePage(1,10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }
}
